package com.pinhuba.bams.framework.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.message.BasicNameValuePair;

import com.pinhuba.bams.framework.exception.NetworkException;
import com.pinhuba.bams.framework.exception.TimeoutException;
import com.pinhuba.bams.framework.util.Loger;

public class HttpPostUtil {

	/**
	 * build HttpUriRequest
	 * 
	 * @param uri
	 * @param hmParams
	 * @return
	 */
	private static HttpUriRequest buildHttpUriRequest(String uri,
			HashMap<String, String> hmParams) throws IllegalArgumentException {
		/*
		 * 下面代码为了输出url地址
		 */
		StringBuffer sb = new StringBuffer();
		sb.append(uri).append("?");
		boolean isFirstParam = true;

		HttpPost post = new HttpPost(uri);
		List<BasicNameValuePair> nameValuePair = new ArrayList<BasicNameValuePair>();
		Iterator<Entry<String, String>> iter = hmParams.entrySet().iterator();
		while (iter.hasNext()) {
			
			if (!isFirstParam) {
				sb.append("&");
			} else {
				isFirstParam = false;
			}
			
			Entry<String, String> entry = iter.next();
//			Loger.d("The params is: " + entry.getKey() + ";" + entry.getValue()
//					+ "   ");
			/*
			 * 下面代码为了输出url地址
			 */
			try {
//				sb.append(URLEncoder.encode(entry.getKey(), BaseHttp.ENCODING));
				sb.append(entry.getKey());
				sb.append("=");
				String value = entry.getValue();
				if (value == null) {
					value = "";
					Loger.e("Key - value是空的 ------" + entry.getKey());
				}
				sb.append(URLEncoder.encode(value, BaseHttp.ENCODING));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			
			nameValuePair.add(new BasicNameValuePair(entry.getKey(), entry
					.getValue()));
		}
		
		Loger.d("这个可能是url请求地址："+sb);
		
		try {
			UrlEncodedFormEntity urlEncode = new UrlEncodedFormEntity(
					nameValuePair, BaseHttp.ENCODING);
			post.setEntity(urlEncode);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			throw new IllegalArgumentException(e);
		}
		return post;
	}

	/**
	 * Executive Request, HttpPost default ENCODING method for parameters in the
	 * BaseHttp ENCODING
	 * 
	 * @param url
	 * @param hmParams
	 * @return HttpUriRequest
	 * @throws TimeoutException
	 *             ,NetworkException
	 */
	public static String executeRequest(String url,
			HashMap<String, String> hmParams) throws TimeoutException,
			NetworkException, IOException {
		Loger.d("The URL is:  " + url );
		return BaseHttp.sendRequest(buildHttpUriRequest(url, hmParams));
	}

}
